package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Host;

public class MetricMemoryManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public MetricMemoryManage(DBConn db)
	{
		this.db=db;
	}
	public MetricMemoryManage(DBPool dbpool)
	{
		this.dbpool=dbpool;
	}
	
	public ResultSet getData(int HostID)
	{
		String sql="select * from Metric_Memory where HostID="+HostID+" order by CollectTime desc LIMIT 1";
		//System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public ResultSet getData(int HostID,String start,String end)
	{
		String sql="select * from Metric_Memory where CollectTime>'"+start+"' and CollectTime<'"+end+"' and HostID="+HostID+" order by collectTime asc";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String addRecord(int HostID,Host host,String collectTime)
	{
		int swap_total=Integer.parseInt(host.getMetric("swap_total"));
		int swap_free=Integer.parseInt(host.getMetric("swap_free"));
		int mem_total=Integer.parseInt(host.getMetric("mem_total"));
		int mem_free=Integer.parseInt(host.getMetric("mem_free"));
		int mem_cached=Integer.parseInt(host.getMetric("mem_cached"));
		int mem_buffers=Integer.parseInt(host.getMetric("mem_buffers"));
		int mem_shared=Integer.parseInt(host.getMetric("mem_shared"));
		
		String sql="insert into Metric_Memory (HostID,swap_total,swap_free,mem_total,mem_free,mem_cached,mem_buffers,mem_shared,CollectTime) values ("+HostID+","+swap_total+","+swap_free+","+mem_total+","+mem_free+","+mem_cached+","+mem_buffers+","+mem_shared+",'"+collectTime+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		} catch (Exception e)
		{
			return "Fail";
		}
	}

	public String deleteRecord(int HostID)
	{
		String sql="delete from Metric_Memory where HostID="+HostID;
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String start,String end)
	{
		String sql="delete from Metric_Memory where CollectTime>'"+start+"' and CollectTime<'"+end+"'";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
